package com.nf.practice.downloadFile;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DownloadPdf {

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 从网络Url中下载文件
     * @param urlStr
     * @param fileName
     * @param savePath
     * @throws IOException
     */
    public static void downLoadByUrl(String urlStr,String fileName,String savePath) throws IOException{
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        //设置超时间为3秒
        conn.setConnectTimeout(5*1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        //得到输入流
        InputStream inputStream = conn.getInputStream();
        //获取自己数组
        byte[] getData = readInputStream(inputStream);
        //文件保存位置
        File saveDir = new File(savePath);
        if(!saveDir.exists()){
            saveDir.mkdir();
        }
        File file = new File(saveDir+File.separator+fileName);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(getData);
        if(fos!=null){
            fos.close();
        }
        if(inputStream!=null){
            inputStream.close();
        }
        System.out.println("info:"+url+" download success");

    }


    /**
     * 从输入流中获取字节数组
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static  byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

    @Test
    public void test03() {
        // 3、通过单号查询该单号下的所有影像件
        // 影像件生产地址
        String picUrl = "http://192.168.40.78:8081";
        List<String> appNoList = Arrays.asList(
                "02202109221022414688",
                "03202107231022354990",
                "01202106101305032673"
        );

        // 测试地址
//        String picUrl = "http://172.16.10.5:31312";
//        List<String> appNoList = Arrays.asList("01202312141557421008");
        for (String appNo : appNoList) {

            Map<String,Object> reqMap = new HashMap<>();
            reqMap.put("appNo", appNo);

            String json = JSON.toJSONString(reqMap);
            CloseableHttpClient client = HttpClients.createDefault();
            HttpPost post = new HttpPost(picUrl + "/file-system/picture/queryImgListAll");
            String response = null;
            try {
                StringEntity s = new StringEntity(json);
                s.setContentEncoding("UTF-8");
                s.setContentType("application/json");//发送json数据需要设置contentType
                post.setEntity(s);
                HttpResponse res = client.execute(post);
                if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                    response = EntityUtils.toString(res.getEntity());
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }

            JSONObject jsonData = JSONObject.parseObject(response);
            List<JSONObject> list = JSONObject.parseArray(jsonData.getJSONArray("data").toJSONString(), JSONObject.class);

            try {
                Long begin = System.currentTimeMillis();
                for (int i = 0; i < list.size(); i++) {
                    String url = list.get(i).getString("filePath");
                    String name = list.get(i).getString("appNo");
                    String fileNames = list.get(i).getString("fileName");
                    downLoadByUrl(url, fileNames,"E:/file/" + name);
                }
                System.out.println("计算耗时：" + (System.currentTimeMillis() - begin) + "ms");
            }catch (Exception e) {
                e.printStackTrace();
            }

        }


    }

    @Test
    public void test02() {
        // 2、读取excel表格再根据文件地址查询影像件系统下载合同
        try{
            String fileName = "E:/upload/影像URL.xlsx";
            // 读取到的数据
            List<FileData> list = EasyExcel.read(fileName)
                    .head(FileData.class)
                    .sheet()
                    .doReadSync();
            Long begin = System.currentTimeMillis();
            for (int i = 0; i < list.size(); i++) {
                if (i > 526) {
                    String url = list.get(i).getUrl();
                    String name = list.get(i).getApp_no();
                    String fileNames = url.substring(url.lastIndexOf("/"));
                    downLoadByUrl(url, fileNames,"E:/file/" + name);
                }
            }
            System.out.println("计算耗时：" + (System.currentTimeMillis() - begin) + "ms");
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test01() {
        // 1、读取excel表格再根据文件地址查询影像件系统下载合同
        try{
            String fileName = "E:/upload/0424.xls";
            // 读取到的数据
            List<ContractData> list = EasyExcel.read(fileName)
                    .head(ContractData.class)
                    .sheet()
                    .doReadSync();
            for (ContractData data : list) {
                if (StringUtils.isBlank(data.getPdf_url())) {
                    continue;
                }
                if (StringUtils.isBlank(data.getContract_no())) {
                    continue;
                }
                String url = data.getPdf_url();
                String name = data.getContract_no() + ".pdf";
                downLoadByUrl(url, name,"E:/contract");
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
